
// Sound system

function initSounds() {
  var audioContext;
  this.introLength = 14000;
  try {
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    audioContext = new window.AudioContext();
  } catch (e) {
    // console.log("initSounds: No Web Audio API support");
    this.loadingPercentageMax += 10;
    return;
  }

  var __self = this;
  this.audioManager = {
    context: audioContext,
    mainVolume: audioContext.createGain(),
    masterVolume: audioContext.createGain(),

    backgroundURL: 'http://localhost:5000/img/sounds/background.mp3',
    explosionURL: 'http://localhost:5000/img/sounds/explosion.mp3',
    soundEffectURLs: [
      'http://localhost:5000/img/sounds/01.mp3',
      'http://localhost:5000/img/sounds/02.mp3',
      'http://localhost:5000/img/sounds/03.mp3',
      'http://localhost:5000/img/sounds/04.mp3',
      'http://localhost:5000/img/sounds/05.mp3',
      'http://localhost:5000/img/sounds/06.mp3',
      'http://localhost:5000/img/sounds/07.mp3',
      'http://localhost:5000/img/sounds/08.mp3',
      'http://localhost:5000/img/sounds/09.mp3'
    ],

    loadSound: function(soundFileName, onload, onerror) {
      var ctx = this.context;
      var mainVolume = this.mainVolume;
      var self = this;

      // Create an object with a sound source and a volume control.
      var sound = {};
      sound.source = ctx.createBufferSource();
      sound.volume = ctx.createGain();

      // Connect the sound source to the volume control.
      sound.source.connect(sound.volume);
      // Hook up the sound volume control to the main volume.
      sound.volume.connect(mainVolume);

      var request = new XMLHttpRequest();
      request.open("GET", soundFileName, true);
      request.responseType = "arraybuffer";
      request.onload = function(e) {

        // Create a buffer from the response ArrayBuffer.
        ctx.decodeAudioData(this.response, function onSuccess(buffer) {
          sound.buffer = buffer;

          // Make the sound source use the buffer.
          sound.source.buffer = sound.buffer;

          onload.call(self, sound);
        }, function onFailure() {
          onerror.call(self, sound);
          console.log("Decoding the audio buffer failed");
        });
      };
      request.onerror = function() {
        onerror.call(self, sound);
      }
      request.send();
    },

    soundEffects: [],
    soundsPlaying: 0,
    playSoundEffect: function(index) {
      if (!this.started || this.soundsPlaying > 5) {
        return;
      }
      index = Math.floor(index) % this.soundEffects.length;
      if (index < 0) {
        index += this.soundEffects.length;
      }
      var sound = this.soundEffects[index];
      if (sound) {
        var node = this.context.createBufferSource();
        var gain = this.context.createGain();
        gain.gain.value = Math.random()*0.1+0.1;
        node.buffer = sound.buffer;
        node.connect(gain);
        gain.connect(sound.volume);
        node.start(this.context.currentTime);
        var self = this;
        this.soundsPlaying++;
        setTimeout(function() {
          self.soundsPlaying--;
        }, 500);
      }
    },

    playRandomSoundEffect: function() {
      this.playSoundEffect(this.soundEffects.length * Math.random());
    },

    getMuted: function() {
      return this.mainVolume.gain.value === 0;
    },

    setMuted: function(muted) {
      this.mainVolume.gain.value = muted ? 0 : 1;
      localStorage.audioMuted = !!muted;
    },

    toggleMuted: function() {
      this.setMuted( !this.getMuted() );
    },

    start: function() {
      if (!this.started) {
        this.started = true;
        this.masterVolume.connect(this.context.destination);
        this.mainVolume.connect(this.masterVolume);
        if (this.explosionSound) {
          this.explosionSound.source.start(this.context.currentTime);
        }

        console.log(this.explosionSound, this.backgroundSound)
        if (this.backgroundSound) {
          this.backgroundSound.source.start(this.context.currentTime);
          this.backgroundSound.volume.gain.setValueAtTime(1, this.context.currentTime + (__self.introLength-3000)/1000);
          this.backgroundSound.volume.gain.linearRampToValueAtTime(0, this.context.currentTime + (__self.introLength+3000)/1000);
        }
      }
    }
  };

  this.audioManager.loadSound(this.audioManager.backgroundURL, function(sound) {
    this.backgroundSound = sound;
  });

  this.audioManager.loadSound(this.audioManager.explosionURL, function(sound) {
    this.explosionSound = sound;
    __self.loadingPercentageMax += 10;
  }, function() {
    __self.loadingPercentageMax += 10;
  });

  for (var i=0; i<this.audioManager.soundEffectURLs.length; i++) {
    var url = this.audioManager.soundEffectURLs[i];
    this.audioManager.loadSound(url, function(sound) {
      this.soundEffects.push(sound);
    });
  }

  this.audioManager.setMuted(localStorage.audioMuted === 'true');

  return this;
}
// audio.audioManager.start();
var audio = initSounds()

document.addEventListener('click', function () {
  audio.audioManager.start();
})
console.log(audio.audioManager)
